package com.hantang.web.json.handlers;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson; 
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.res.StringRes;



public abstract class AbstractHandler extends HttpHandler implements
		HttpHandlerConstants {

	
	private static Logger logger = Logger.getLogger(AbstractHandler.class);

	public abstract String doService(Request req, Response resp)
			throws Exception;

	@Override
	public void service(Request req, Response resp) throws Exception {

		String result = "";
		try {
			boolean isJsonp = false;
			logger.info("request URL: " + req.getRequestURL().toString());
			result = doService(req, resp);
			
			if (result == null) {
				result = "";
			}
			String returnType = req.getParameter(PARA_RETURN_TYPE);
			String callBack = "";
			if(returnType!= null && returnType.trim().equals(VALUE_RETURN_TYPE))
			{
				isJsonp = true;
				callBack = req.getParameter(PARA_CALL_BACK);
				if(callBack==null)
				{
					callBack ="";
				}
			}
			
			if(isJsonp){
				result = callBack + "(" + result + ")";	
			}
//			logger.info("result:" + result);
			
			resp.setCharacterEncoding("UTF-8");		
			
			byte bs[] = result.getBytes("UTF-8");
			resp.setContentLength(bs.length);
			resp.getOutputStream().write(bs);
		} catch (Exception e) {
			logger.error("Exceptiion: " ,e );
			throw e;
		} finally {
			//resp.get
		}

	}

	
	public static String generateStringResponse(String str)
	{
		
		StringRes sres = new StringRes();
    	if(str != null)
    	{
    		sres.setData(str);
    		sres.setMeta(new MetaData(MetaData.META_DATA_SUCCESS_CODE, "Succ"));
    	}else{
    		sres.setMeta(new MetaData(MetaData.META_DATA_FAILED_CODE, "Failed"));
    	}		
		
		return new Gson().toJson(sres);
	}
	
	
	
}
